package com.book.utils;

import java.util.Random;

public class CodeTool {
    private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
    private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
    private static final String DIGITS = "0123456789";
    private static final int LENGTH = 6;

    /**
     *
     * @return 返回一个6位字符的验证码
     */
    public static String getCaptcha(){//获取验证码
        StringBuilder captchaBuilder = new StringBuilder(LENGTH);
        Random random = new Random();
        for (int i = 0; i < LENGTH; i++) {
            // 随机选择字符类型
            int type = random.nextInt(3);
            switch (type) {
                case 0:
                    // 添加小写字母
                    captchaBuilder.append(CHAR_LOWER.charAt(random.nextInt(CHAR_LOWER.length())));
                    break;
                case 1:
                    // 添加大写字母
                    captchaBuilder.append(CHAR_UPPER.charAt(random.nextInt(CHAR_UPPER.length())));
                    break;
                case 2:
                    // 添加数字
                    captchaBuilder.append(DIGITS.charAt(random.nextInt(DIGITS.length())));
                    break;
            }
        }
        return captchaBuilder.toString();
    }
}
